<?php

namespace app\index\controller;


use think\Controller;
use think\Request;
use think\Db;
//use think\Session;
//use think\Cookie;
use think\facade\Session;
use think\facade\Cookie;
use app\index\model\Wechat;
use app\common\entity\User;
// use app\common\entity\MyWallet;
use app\common\entity\UserInviteCode;

use app\common\service\Users\Identity;



class Wechatlogin extends Controller
{
    public function we_login(Request $request){
//        file_put_contents(dirname(__FILE__).'/log',json_encode(111));

        // file_put_contents('/www/wwwroot/xfb/aaa1.txt', json_encode($request->get('code')).date('H:i:s').PHP_EOL,FILE_APPEND);
        // echo Session::get('pid');
        // exit;
        // $appid = \app\common\entity\Config::getOneValue('appid');;  //微信公众平台->开发->基本配置->AppID

        // $appKey = \app\common\entity\Config::getOneValue('secert');;   //微信公众平台->开发->基本配置->AppSecret
        $appid = 'wxb0b4d659b6ad8d81';
        $appKey = '0a0401320fa2cb3bf7909584ca95bd79';
        $wxPay = new Wechat($appid,$appKey);

        // Cookie::set('w_code',$request->get('code'),300);

        $code = Cookie::get('w_code');

//        file_put_contents(dirname(__FILE__).'/request',json_encode(input()));

        if($code == $request->get('code')){
            // echo Session::get('target_url');
//            $this->redirect(Session::get('target_url'));
//            exit;
        }

        $data = $wxPay->GetOpenid($request->get('code'));


        if(!$data['openid']) exit('获取openid失败');

        // echo Session::get('target_url');
        // exit;

        $user = User::where('openid',$data['openid'])->find();
        //file_put_contents(dirname(__FILE__).'/user',json_encode($user));
        // echo Session::get('pid');
        $url_to = '/dist/#/Login';
//        http://1225blz.qykj2020.cn/dist/#/Login
        if($user){

            $identity = new Identity();
            $identity->saveSession($user);
            $login_time = session_id();
            \app\common\entity\User::where('id', $user['id'])->update(['login_time' => $login_time]);
            session('login_time', $login_time);

            //file_put_contents(dirname(__FILE__).'/login_time'.$user['openid'],json_encode($login_time));
            // $this->redirect(Session::get('target_url'));
            $url_to .= '?token='.$login_time;
            $this->redirect($url_to);
            exit;
        }else{

            $wechat_info = $wxPay->getUserInfo($data['openid'],$data['access_token']);
            //file_put_contents(dirname(__FILE__).'/wechat_info',json_encode($wechat_info));
            $pid = Session::get('pid')?Session::get('pid'):0;



//            $id = User::insertGetId(['openid' => $data['openid'] , 'pid' => $pid , 'avatar' => $wechat_info['headimgurl'] , 'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $wechat_info['nickname']) , 'register_time' => time() , 'register_ip' => $request->ip()]);
            $datas = [
                'openid' => $data['openid'] ,
                'pid' => $pid ,
                'avatar' => $wechat_info['headimgurl'] ,
                'nick_name' => preg_replace('/[\x{10000}-\x{10FFFF}]/u', '', $wechat_info['nickname']) ,
                /*'register_time' => time() ,
                'register_ip' => $request->ip()*/
            ];
            $model = new \app\index\model\User();
            $id = $model->doRegister($datas);
            if($id){


//                $inviteCode = new UserInviteCode();
//
//                $inviteCode->saveCode($id);

                $user = User::where('openid',$data['openid'])->find();

                $identity = new Identity();
                $identity->saveSession($user);
                $login_time = session_id();
                \app\common\entity\User::where('id', $id)->update(['login_time' => $login_time]);
                session('login_time', $login_time);
                $url_to .= '?token='.$login_time;
                $this->redirect($url_to);
                exit;
            }else{

                exit('获取openid失败');

            }


            // $this->doRegisters($data);

        }


    }
    /**
     * [扫码注册]
     * @return
     */
    public function qrcode(Request $request){
        $pid = input('pid');
        if(!empty($pid)) {
            Session::set('pid',$pid);
        }
        $appid = 'wxb0b4d659b6ad8d81';
        $appKey = 'a5b2fb6d101229537bf89f3014da51cd';
        (new Wechat($appid,$appKey))->GetOpenid();
        return;
    }


}
